package com.heima.user.service.impl;

import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.excel.UserExcel;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.listens.CommonListen;
import com.heima.user.mapper.ApUserPhoneMapper;
import com.heima.user.mapper.UserExcelMapper;
import com.heima.user.service.ApUserService;
import com.heima.user.service.UserExcelService;
import com.heima.utils.common.MD5Utils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.json.Json;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.net.URLEncoder;
import java.util.*;
import java.util.concurrent.TimeUnit;


@Service
@Slf4j
public class UserExcelServiceImpl extends ServiceImpl<UserExcelMapper, UserExcel> implements UserExcelService {

    @Autowired
    private ApUserService apUserService;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private ApUserPhoneMapper apUserPhoneMapper;
    @Autowired
    UserExcelMapper userExcelMapper;

    //获取url链接上的参数
    @Override
    public ResponseResult simpleWrite(HttpServletResponse response, @RequestParam("repetitionId") String name) {

        response.setContentType("application/binary;charset=UTF-8");
        try {
            ServletOutputStream out = response.getOutputStream();
            try {
                response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(name + ".xlsx", "UTF-8"));
            } catch (UnsupportedEncodingException e1) {
                e1.printStackTrace();
            }
            String range = String.valueOf(redisTemplate.opsForList().range(name, 0, -1));
            List<UserExcel> userExcels = JSON.parseArray(range, UserExcel.class);
            EasyExcel.write(out, UserExcel.class).sheet().doWrite(userExcels);
            return ResponseResult.okResult(userExcels);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "导出失败");
        }
    }

    @Override
    public ResponseResult simpleRead(MultipartFile file) {
        ApUser adminUser = AppThreadLocalUtils.getUser();
        int repetitionNumber = 0;
        int successNumber = 0;
        CommonListen<UserExcel> commonListen = new CommonListen<UserExcel>(UserExcel.class);
        try {
            EasyExcel.read(file.getInputStream(), UserExcel.class, commonListen).sheet().doRead();
            // 获取导入的数据集合
            List<UserExcel> list = commonListen.getList();
            Set<UserExcel> set = new HashSet<>(list.size());
            List<UserExcel> repaeList = new ArrayList<>();
            List<UserExcel> list2 = new ArrayList<>(list.size());
            //遍历
            for (UserExcel userExcel : list) {
                ApUser apUser = apUserPhoneMapper.findByPhone(userExcel.getPhone());
                if (apUser!=null) {
                    repaeList.add(userExcel);
                } else {
                    String password = userExcel.getPassword();
                    String md5 = userExcel.getSalt();
                    userExcel.setPassword(MD5Utils.encodeWithSalt(password, md5));
                    if ("男".equals(userExcel.getSex())) {
                        userExcel.setSex("1");
                    } else {
                        userExcel.setSex("0");
                    }
                    boolean boo = set.add(userExcel);
                    if (boo == false) {
                        repaeList.add(userExcel);
                    }
                }
            }
            repetitionNumber = repaeList.size();
            successNumber = set.size();
            if(set!=null&&set.size()>0){
                list2.addAll(set);
                userExcelMapper.insertExcel(list2);
            }
            for (UserExcel userExcel : repaeList) {
                String fails = JSON.toJSONString(userExcel);
                redisTemplate.opsForList().leftPush(String.valueOf(adminUser.getId()), fails);
                redisTemplate.expire(String.valueOf(adminUser.getId()), 1L, TimeUnit.MINUTES);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        Map<String, Integer> map = new HashMap<>();
        map.put("repetitionNumber", repetitionNumber);
        map.put("successNumber", successNumber);
        map.put("repetitionId", adminUser.getId());
        return ResponseResult.okResult(map);
    }
}
